<template>
    <div class="orders-container" style="margin-bottom: 50px; padding-bottom: 10px;">
        <van-nav-bar title="历史订单" fixed />

        <!-- 搜索栏 -->
        <div class="search-section">
            <van-search v-model="searchQuery" placeholder="搜索订单关键词" @search="onSearch" />
        </div>

        <!-- 订单列表 -->
        <div class="order-section">
            <div class="section-header">
                <div class="tab-container">
                    <div :class="['tab-item', { active: activeTab === 'all' }]" @click="switchTab('all')">
                        全部订单
                    </div>
                    <div v-if="isEmployer" :class="['tab-item', { active: activeTab === 'myPublished' }]"
                        @click="switchTab('myPublished')">
                        我发布的
                    </div>
                    <div v-else :class="['tab-item', { active: activeTab === 'myAccepted' }]"
                        @click="switchTab('myAccepted')">
                        我接受的
                    </div>
                </div>
            </div>

            <div class="order-cards">
                <van-card v-for="order in displayOrders" :key="order.orderId" :price="order.orderAmount"
                    price-label="订单金额" :title="getOrderTitle(order)" @click="viewOrderDetail(order.orderId)">
                    <template #tags>
                        <div class="order-tags">
                            <van-tag plain :type="getOrderStatusType(order.orderStatus)">
                                {{ getOrderStatusText(order.orderStatus) }}
                            </van-tag>
                            <van-tag plain :type="getPaymentStatusType(order.paymentStatus)">
                                {{ getPaymentStatusText(order.paymentStatus) }}
                            </van-tag>
                        </div>
                    </template>

                    <template #desc>
                        <div class="order-info">
                            <div class="info-item">
                                <van-icon name="cash-o" />
                                <span>实付金额：¥{{ order.actualAmount.toFixed(2) }}</span>
                            </div>
                            <div class="info-item">
                                <van-icon name="clock-o" />
                                <span>{{ order.startTime }} 至 {{ order.endTime }}</span>
                            </div>
                            <div class="info-item" v-if="order.orderStatus === -1">
                                <van-icon name="warning-o" />
                                <span>取消原因：{{ order.cancelReason || '无' }}</span>
                            </div>
                        </div>
                    </template>

                    <template #footer>
                        <div class="order-footer">
                            <div class="order-parties">
                                <div class="party-info">
                                    <van-image round width="20" height="20" 
                                        :src="order.employerAvatarSrc || ''" />
                                    <span>雇主：{{ getUserName(order.employerId) }}</span>
                                </div>
                                <div class="party-divider">|</div>
                                <div class="party-info" v-if="order.workerId">
                                    <van-image round width="20" height="20" 
                                        :src="order.workerAvatarSrc || ''" />
                                    <span>工人：{{ getUserName(order.workerId) }}</span>
                                </div>
                            </div>
                            <div class="order-time">{{ formatTime(order.createTime) }}</div>
                        </div>
                    </template>

                    <template #bottom>
                        <div class="order-bottom">
                            <div class="order-id">
                                <span>订单号：{{ order.orderId }}</span>
                            </div>

                            <!-- 根据当前标签和订单状态显示不同的按钮 -->
                            <template v-if="activeTab === 'all'">
                                <van-button color="#4f46e5" type="primary" size="small"
                                    @click.stop="viewOrderDetail(order.orderId)">查看详情</van-button>
                            </template>

                            <template v-else-if="activeTab === 'myPublished'">
                                <!-- 根据订单状态显示不同的操作按钮 -->
                                <div class="action-buttons">
                                    <template v-if="order.paymentStatus === 0">
                                        <!-- 待支付状态 -->
                                        <van-button color="#4f46e5" type="primary" size="mini"
                                            @click.stop="goToPayment(order.orderId)">支付</van-button>
                                    </template>
                                    <template v-else-if="order.orderStatus === 1">
                                        <!-- 进行中状态 -->
                                        <van-button color="#4f46e5" type="primary" size="mini"
                                            @click.stop="completeOrder(order.orderId)">完成订单</van-button>
                                    </template>
                                    <template v-else-if="order.orderStatus === 2">
                                        <!-- 已完成状态 -->
                                        <van-button color="#10b981" plain size="mini" disabled>已完成</van-button>
                                    </template>
                                    <template v-else-if="order.orderStatus === -1">
                                        <!-- 已取消状态 -->
                                        <van-button color="#64748b" plain size="mini" disabled>已取消</van-button>
                                    </template>

                                    <!-- 如果订单未开始且未取消，显示取消按钮 -->
                                    <van-button v-if="order.orderStatus === 0 || order.orderStatus === 1" 
                                        color="#4f46e5" plain size="mini"
                                        @click.stop="cancelOrder(order.orderId)">取消</van-button>
                                </div>
                            </template>

                            <template v-else-if="activeTab === 'myAccepted'">
                                <!-- 我接受的订单操作按钮 -->
                                <div class="action-buttons">
                                    <template v-if="order.orderStatus === 1">
                                        <!-- 进行中状态 -->
                                        <van-button color="#4f46e5" type="primary" size="small"
                                            @click.stop="contactEmployer(order.employerId)">联系雇主</van-button>
                                    </template>
                                    <template v-else-if="order.orderStatus === 2">
                                        <!-- 已完成状态 -->
                                        <van-button color="#10b981" plain size="small" disabled>已完成</van-button>
                                    </template>
                                    <template v-else-if="order.orderStatus === -1">
                                        <!-- 已取消状态 -->
                                        <van-button color="#64748b" plain size="small" disabled>已取消</van-button>
                                    </template>
                                </div>
                            </template>
                        </div>
                    </template>
                </van-card>
            </div>

            <!-- 空状态提示 -->
            <div v-if="displayOrders.length === 0" class="empty-state">
                <van-empty :description="getEmptyStateDescription()" image="search">
                    <template #bottom>
                        <van-button v-if="activeTab === 'myPublished' && isEmployer" round type="primary"
                            @click="goToTaskList">
                            去浏览任务
                        </van-button>
                    </template>
                </van-empty>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'
import network from '../network'

const router = useRouter()

// 搜索
const searchQuery = ref('')
// 在script部分添加订单接口
interface Order {
    orderId: number;
    orderAmount: number;
    actualAmount: number;
    taskId: number;
    orderStatus: number;
    paymentStatus: number;
    startTime: string;
    endTime: string;
    createTime: string;
    employerId: number;
    workerId?: number;
    cancelReason?: string;
    employerAvatarSrc?: string;
    workerAvatarSrc?: string;
}

// 修改ref定义，使用接口类型
const orders = ref<Order[]>([]);
const myPublishedOrders = ref<Order[]>([]);
const myAcceptedOrders = ref<Order[]>([]);
const currentUser = ref<any>(null)
const activeTab = ref('all')

// 根据当前选中的标签显示对应的订单列表
const displayOrders = computed(() => {
    if (activeTab.value === 'myPublished') {
        return myPublishedOrders.value
    } else if (activeTab.value === 'myAccepted') {
        return myAcceptedOrders.value
    } else {
        return orders.value
    }
})

const getEmptyStateDescription = () => {
    if (activeTab.value === 'all') {
        return '暂无订单记录'
    } else if (activeTab.value === 'myPublished') {
        return '您还没有发布订单'
    } else if (activeTab.value === 'myAccepted') {
        return '您还没有接受订单'
    }
    return '暂无数据'
}

// 切换标签
const switchTab = (tab: string) => {
    activeTab.value = tab
    if (tab === 'myPublished' && myPublishedOrders.value.length === 0) {
        loadMyPublishedOrders()
    } else if (tab === 'myAccepted' && myAcceptedOrders.value.length === 0) {
        loadMyAcceptedOrders()
    }
}

// 判断当前用户是否为雇主
const isEmployer = computed(() => {
    return currentUser.value && currentUser.value.userType === 1
})

// 获取用户姓名
const getUserName = (userId: number) => {
    // 实际项目中应该从后端获取用户信息
    return `${userId}`
}

// 获取订单标题
const getOrderTitle = (order: any) => {
    // 实际项目中应该从关联的任务中获取标题
    return `任务订单 #${order.taskId}`
}

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
    const statuses = {
        '-1': '已取消',
        '0': '待开始',
        '1': '进行中',
        '2': '已完成'
    }
    return statuses[status.toString() as keyof typeof statuses] || '未知状态'
}

// 获取订单状态类型
const getOrderStatusType = (status: number) => {
    const types = {
        '-1': 'danger',
        '0': 'primary',
        '1': 'warning',
        '2': 'success'
    }
    return types[status.toString() as keyof typeof types] || 'default'
}

// 获取支付状态文本
const getPaymentStatusText = (status: number) => {
    const statuses = {
        '0': '待支付',
        '1': '已支付',
        '2': '已退款'
    }
    return statuses[status.toString() as keyof typeof statuses] || '未知状态'
}

// 获取支付状态类型
const getPaymentStatusType = (status: number) => {
    const types = {
        '0': 'warning',
        '1': 'success',
        '2': 'primary'
    }
    return types[status.toString() as keyof typeof types] || 'default'
}

// 格式化时间
const formatTime = (timeString: string) => {
    if (!timeString) return ''

    const now = new Date()
    const time = new Date(timeString)
    const diff = now.getTime() - time.getTime()

    // 小于1小时
    if (diff < 3600000) {
        const minutes = Math.floor(diff / 60000)
        return `${minutes}分钟前`
    }
    // 小于24小时
    else if (diff < 86400000) {
        const hours = Math.floor(diff / 3600000)
        return `${hours}小时前`
    }
    // 小于30天
    else if (diff < 2592000000) {
        const days = Math.floor(diff / 86400000)
        return `${days}天前`
    }
    // 大于30天
    else {
        const year = time.getFullYear()
        const month = time.getMonth() + 1
        const day = time.getDate()
        return `${year}-${month}-${day}`
    }
}

// 搜索订单
const onSearch = () => {
    // 搜索订单
    network.searchOrders(searchQuery.value)
        .then((res: any) => {
            if (res.code === 100) {
                orders.value = res.data
            } else {
                showToast(res.message || '搜索订单失败')
            }
        })
}

// 加载所有订单
const loadOrders = async () => {
    try {
        network.getOrderList()
            .then((res: any) => {
                if (res.code === 100) {
                    orders.value = res.data;
                    loadAvatarsForOrders(orders.value); // 加载头像
                } else {
                    showToast(res.message || '获取订单列表失败');
                }
            }).catch((error) => {
                console.error('获取订单列表失败:', error);
                showToast('获取订单列表失败，请稍后重试');
            });
    } catch (error) {
        console.error('获取订单失败:', error);
        showToast('获取订单失败，请稍后重试');
    }
};

// 加载我发布的订单
const loadMyPublishedOrders = async () => {
    try {
        if (!currentUser.value || !currentUser.value.userId) {
            showToast('请先登录');
            return;
        }

        network.getMyPublishedOrders()
            .then((res: any) => {
                if (res.code === 100) {
                    myPublishedOrders.value = res.data;
                    loadAvatarsForOrders(myPublishedOrders.value); // 加载头像
                } else {
                    showToast(res.message || '获取我发布的订单失败');
                }
            });
    } catch (error) {
        console.error('获取我发布的订单失败:', error);
        showToast('获取我发布的订单失败，请稍后重试');
    }
};

// 加载我接受的订单
const loadMyAcceptedOrders = async () => {
    try {
        if (!currentUser.value || !currentUser.value.userId) {
            showToast('请先登录');
            return;
        }

        network.getMyAcceptedOrders()
            .then((res: any) => {
                if (res.code === 100) {
                    myAcceptedOrders.value = res.data;
                    loadAvatarsForOrders(myAcceptedOrders.value); // 加载头像
                } else {
                    showToast(res.message || '获取我接受的订单失败');
                }
            });
    } catch (error) {
        console.error('获取我接受的订单失败:', error);
        showToast('获取我接受的订单失败，请稍后重试');
    }
};

// 查看订单详情
const viewOrderDetail = (orderId: number) => {
    router.push(`/order-detail/${orderId}`)
}

// 跳转到支付页面
const goToPayment = (orderId: number) => {
    router.push(`/payment/${orderId}`)
}

// 完成订单
const completeOrder = (orderId: number) => {
    showDialog({
        title: '完成确认',
        message: '确定要将此订单标记为已完成吗？',
        showCancelButton: true,
    }).then(() => {
        network.completeOrder(orderId)
            .then((res: any) => {
                if (res.code === 100) {
                    showToast('订单已完成')
                    // 更新订单状态
                    const order = myPublishedOrders.value.find(o => o.orderId === orderId)
                    if (order) {
                        order.orderStatus = 2
                    }
                } else {
                    showToast(res.message || '操作失败')
                }
            })
            .catch(err => {
                showToast('操作失败，请稍后重试')
                console.error('完成订单失败:', err)
            })
    })
}

// 取消订单
const cancelOrder = (orderId: number) => {
    showDialog({
        title: '取消确认',
        message: '确定要取消该订单吗？取消后将无法恢复。',
        showCancelButton: true,
    }).then(() => {
        network.cancelOrder(orderId)
            .then((res: any) => {
                if (res.code === 100) {
                    showToast('订单已取消')
                    // 更新订单状态
                    const order = myPublishedOrders.value.find(o => o.orderId === orderId)
                    if (order) {
                        order.orderStatus = -1
                    }
                } else {
                    showToast(res.message || '取消订单失败')
                }
            })
            .catch(err => {
                showToast('取消订单失败，请稍后重试')
                console.error('取消订单失败:', err)
            })
    })
}

// 联系雇主
const contactEmployer = (employerId: number) => {
    showToast('联系功能开发中')
}

// 跳转到任务列表
const goToTaskList = () => {
    router.push('/Mtasklist')
}

// 获取当前用户信息
const getCurrentUser = () => {
    try {
        network.getInfo()
            .then((res: any) => {
                if (res.code === 100) {
                    currentUser.value = res.data
                    // 根据用户类型加载不同数据
                    if (currentUser.value && currentUser.value.userType === 1) {
                        loadMyPublishedOrders()
                    } else {
                        loadMyAcceptedOrders()
                    }
                }
            })
            .catch(err => {
                console.error('获取用户信息失败:', err)
            })
    } catch (error) {
        console.error('解析用户信息失败:', error)
    }
}

// 组件挂载时加载数据
onMounted(() => {
    loadOrders()
    getCurrentUser()
})

// 获取并设置单个用户的头像
const fetchAndSetUserAvatar = async (order: Order, userId: number, isEmployer: boolean) => {
    // 检查是否已经加载过头像
    if ((isEmployer && order.employerAvatarSrc) || (!isEmployer && order.workerAvatarSrc)) return;

    try {
        const res: any = await network.getAvatarById(userId);
        if (res.data && res.data.code === 100 && res.data.data && res.data.data.avatarData) {
            // 将获取到的Base64数据赋值
            if (isEmployer) {
                order.employerAvatarSrc = res.data.data.avatarData;
            } else {
                order.workerAvatarSrc = res.data.data.avatarData;
            }
        } else {
            // 设置为空，由模板处理默认头像
            if (isEmployer) {
                order.employerAvatarSrc = '';
            } else {
                order.workerAvatarSrc = '';
            }
            console.warn(`获取用户 ${userId} 头像失败: ${res.data?.message}`);
        }
    } catch (error) {
        // 出错时设置为空
        if (isEmployer) {
            order.employerAvatarSrc = '';
        } else {
            order.workerAvatarSrc = '';
        }
        console.error(`获取用户 ${userId} 头像异常:`, error);
    }
};

// 在订单数据加载或更新后调用此函数来加载头像
const loadAvatarsForOrders = (orderList: Order[]) => {
    orderList.forEach(order => {
        // 加载雇主头像
        fetchAndSetUserAvatar(order, order.employerId, true);
        
        // 如果有工人ID，也加载工人头像
        if (order.workerId) {
            fetchAndSetUserAvatar(order, order.workerId, false);
        }
    });
};

</script>

<style scoped>
.orders-container {
    min-height: 100vh;
    background: linear-gradient(145deg, #f8fafc, #f1f5f9);
    padding-bottom: 50px;
    padding-top: 46px;
}

.search-section {
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(10px);
    padding: 15px;
    margin: 20px;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.order-section {
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(10px);
    margin: 20px;
    border-radius: 16px;
    padding: 20px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.section-header {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.tab-container {
    display: flex;
    gap: 24px;
    position: relative;
}

.tab-item {
    font-size: 18px;
    font-weight: 600;
    color: #64748b;
    padding-bottom: 8px;
    cursor: pointer;
    position: relative;
    transition: all 0.3s ease;
}

.tab-item.active {
    color: #1e293b;
}

.tab-item.active::after {
    content: '';
    position: absolute;
    bottom: -15px;
    left: 0;
    width: 100%;
    height: 3px;
    background: linear-gradient(to right, #4f46e5, #6366f1);
    border-radius: 3px;
}

.order-cards {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

:deep(.van-card) {
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.03);
    padding: 20px;
    margin: 0;
    transition: all 0.3s ease;
    border: 1px solid rgba(0, 0, 0, 0.03);
}

:deep(.van-card:hover) {
    transform: translateY(-2px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

:deep(.van-card__title) {
    font-size: 17px;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 8px;
}

:deep(.van-card__price) {
    font-size: 22px;
    background: linear-gradient(45deg, #4f46e5, #6366f1);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    font-weight: 700;
    display: block;
    text-align: right;
}

:deep(.van-search__content) {
    background: rgba(255, 255, 255, 0.8);
    border-radius: 12px;
    padding: 8px 12px;
}

:deep(.van-search) {
    padding: 0;
    background: transparent;
}

.order-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 8px;
}

.order-info {
    display: flex;
    flex-direction: column;
    gap: 6px;
    margin-top: 8px;
}

.info-item {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 14px;
    color: #64748b;
}

.info-item .van-icon {
    color: #94a3b8;
}

.order-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px dashed #e5e7eb;
}

.order-parties {
    display: flex;
    align-items: center;
    gap: 8px;
}

.party-info {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    color: #64748b;
}

.party-divider {
    color: #e5e7eb;
    font-size: 12px;
}

.order-time {
    font-size: 12px;
    color: #94a3b8;
}

.order-bottom {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 12px;
}

.order-id {
    font-size: 12px;
    color: #94a3b8;
}

.action-buttons {
    display: flex;
    gap: 6px;
}

:deep(.van-button--mini) {
    min-width: 56px;
    height: 28px;
    padding: 0 10px;
    font-size: 12px;
    border-radius: 6px;
}

:deep(.van-button--plain) {
    background-color: transparent;
    border: 1px solid currentColor;
}

:deep(.van-button--plain.van-button--disabled) {
    color: #9ca3af;
    border-color: #9ca3af;
    opacity: 0.6;
}

.empty-state {
    padding: 40px 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}

:deep(.van-empty__image) {
    width: 120px;
    height: 120px;
}

:deep(.van-empty__description) {
    color: #64748b;
    font-size: 16px;
    margin-top: 16px;
}

:deep(.van-button--round) {
    border-radius: 20px;
    padding: 0 24px;
    margin-top: 20px;
}
</style>